package com.xinyi.tangmi;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Random;

import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.alipay.sdk.app.PayTask;
import com.xinyi.tangmi.R;

import android.R.integer;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.FragmentActivity;
import android.text.TextUtils;
import android.util.Base64;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.CheckBox;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

public class PayActivity extends SwipeBackActivity {
	private static final int SDK_PAY_FLAG = 1;
	String rec_ids;
	ArrayList<String> names = new ArrayList<String>();
	ArrayList<String> num = new ArrayList<String>();
	ArrayList<String> price = new ArrayList<String>();
	public static final int GET_ORDER_CMP = 0;
	public static final int GET_ORDER_FAIL = -1;
	public static final int NET_ERR = -5;
	protected static final int CHECK_ORDER = 0;
	private static final int PAY_AGAIN = 4;
	private static final int NO_ADDRES = 6;
	protected static final int FAIL = 7;
	protected static final int SUCCEED = 8;
	protected static final int UPDATA_VIEW = 9;
	RelativeLayout addressLayout;
	LinearLayout itemLayout;
	TextView payTextView, priceTextView, nameTextView, phoneTextView,
			detailTextView;
	Dialog dialog;
	String order_id;
	int selectedBouns = -1;
	ListView bonusList;
	DecimalFormat decimalFormat = new DecimalFormat(".00");
	List<Map<String, String>> bonusMaps = new ArrayList<Map<String, String>>();
	Handler handler = new Handler() {
		public void handleMessage(Message msg) {
			if (dialog != null && dialog.isShowing()) {
				dialog.dismiss();
			}
			switch (msg.what) {
			case PAY_AGAIN:
				payAgain(order_id);
				break;
			case FAIL:
				bonusList.setVisibility(View.GONE);
				break;
			case SUCCEED:
				if (bonusList.getAdapter() == null) {
					SimpleAdapter simpleAdapter = new SimpleAdapter(
							getApplicationContext(), bonusMaps,
							R.layout.bonus_item_pay, new String[] {
									"type_name", "type_money", "bonus_sn",
									"use_end_date", "min_goods_amount" },
							new int[] { R.id.bonus_name, R.id.bonus_price,
									R.id.bonus_number, R.id.bonus_date,
									R.id.min_require });
					bonusList.setAdapter(simpleAdapter);
				} else {
					((SimpleAdapter) bonusList.getAdapter())
							.notifyDataSetChanged();
				}
				handler.postAtTime(new Runnable() {

					@Override
					public void run() {
						// TODO Auto-generated method stub
						handler.sendEmptyMessage(UPDATA_VIEW);
					}
				}, 300);
				break;
			case GET_ORDER_CMP:
				pay();
				break;
			case UPDATA_VIEW:
				if (bonusList.getCount() > 0 && bonusList.getChildCount() > 0) {
					ViewGroup.LayoutParams layoutParams = (ViewGroup.LayoutParams) bonusList
							.getLayoutParams();
					layoutParams.height = bonusList.getChildAt(0).getHeight()
							* bonusList.getCount();
					Log.i("height", layoutParams.height + "");
					bonusList.setLayoutParams(layoutParams);
				}
				break;
			case NO_ADDRES:
				Toast.makeText(getApplicationContext(), "请设置默认收货地址", 0).show();
				Intent intent = new Intent(getApplicationContext(),
						AddressManageActivity.class);
				startActivity(intent);
				break;
			case GET_ORDER_FAIL:
				Toast.makeText(getApplicationContext(), "订单获取失败", 0).show();
				break;
			case NET_ERR:
				Toast.makeText(getApplicationContext(), "订单获取失败", 0).show();
				break;

			default:
				break;
			}
		};
	};
	String totalFee, payInfo, name, tel, address;

	@SuppressLint("HandlerLeak")
	private Handler mHandler = new Handler() {
		@SuppressWarnings("unused")
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case -1:
				if (dialog != null && dialog.isShowing()) {
					dialog.dismiss();
				}
				Toast.makeText(getApplicationContext(), "订单获取失败", 0).show();
				break;
			case CHECK_ORDER:
				if (dialog != null && dialog.isShowing()) {
					dialog.dismiss();
				}
				nameTextView.setText(name);
				phoneTextView.setText(tel);
				detailTextView.setText(address);
				priceTextView.setText(totalFee);
				itemLayout.removeAllViews();
				for (int i = 0; names != null && num != null && price != null
						&& i < names.size() && i < num.size()
						&& i < price.size(); i++) {
					RelativeLayout item = (RelativeLayout) getLayoutInflater()
							.inflate(R.layout.order_item, null);
					((TextView) item.findViewById(R.id.itemname)).setText(names
							.get(i));
					((TextView) item.findViewById(R.id.itemnum)).setText("×"
							+ num.get(i));
					((TextView) item.findViewById(R.id.itemprice))
							.setText(price.get(i));
					itemLayout.addView(item);
				}
				getHongBao();
				break;
			case SDK_PAY_FLAG: {
				PayResult payResult = new PayResult((String) msg.obj);
				/**
				 * 同步返回的结果必须放置到服务端进行验证（验证的规则请看https://doc.open.alipay.com/doc2/
				 * detail.htm?spm=0.0.0.0.xdvAU6&treeId=59&articleId=103665&
				 * docType=1) 建议商户依赖异步通知
				 */
				String resultInfo = payResult.getResult();// 同步返回�?要验证的信息
				String resultStatus = payResult.getResultStatus();
				Log.i("result", msg.obj.toString());
				// 判断resultStatus 为�??9000”则代表支付成功，具体状态码代表含义可参考接口文�?
				if (TextUtils.equals(resultStatus, "9000")) {
					Toast.makeText(PayActivity.this, "支付成功", Toast.LENGTH_SHORT)
							.show();
					Intent intent = new Intent(getApplicationContext(),
							OrderActivity.class);
					intent.putExtra("index", 2);
					startActivity(intent);
					finish();
				} else {
					// 判断resultStatus 为非"9000"则代表可能支付失�?
					// "8000"代表支付结果因为支付渠道原因或�?�系统原因还在等待支付结果确认，�?终交易是否成功以服务端异步�?�知为准（小概率状�?�）
					if (TextUtils.equals(resultStatus, "8000")) {
						Toast.makeText(PayActivity.this, "支付结果确认中",
								Toast.LENGTH_SHORT).show();
						Intent intent = new Intent(getApplicationContext(),
								OrderActivity.class);
						intent.putExtra("index", 2);
						startActivity(intent);
						finish();
					} else {
						// 其他值就可以判断为支付失败，包括用户主动取消支付，或者系统返回的错误
						Toast.makeText(PayActivity.this, "您已取消支付",
								Toast.LENGTH_SHORT).show();
					}
				}
				break;
			}
			default:
				break;
			}
		};
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
			setTranslucentStatus(true);
			SystemBarTintManager tintManager = new SystemBarTintManager(this);
			tintManager.setStatusBarTintEnabled(true);
			tintManager.setStatusBarTintColor(MainActivity.MainTitileColor);// 通知栏所需颜色
		}
		setContentView(R.layout.activity_confirm_order);
		addressLayout = (RelativeLayout) findViewById(R.id.address);
		itemLayout = (LinearLayout) findViewById(R.id.itemconfirm);
		payTextView = (TextView) findViewById(R.id.pay);
		priceTextView = (TextView) findViewById(R.id.totalPrice);
		nameTextView = (TextView) findViewById(R.id.tv_name);
		phoneTextView = (TextView) findViewById(R.id.tv_phone);
		detailTextView = (TextView) findViewById(R.id.tv_detail);
		bonusList = (ListView) findViewById(R.id.pay_bonus);
		bonusList.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				// TODO Auto-generated method stub
				Log.i("position", arg2 + "");
				if (arg2 >= 0 && arg2 < bonusMaps.size()) {
					priceTextView.setText(decimalFormat.format(Float
							.parseFloat(totalFee)
							- Float.parseFloat(bonusMaps.get(arg2).get(
									"type_money"))));
					if (Float.parseFloat(totalFee) < Float.parseFloat(bonusMaps
							.get(arg2).get("min_amount"))) {
						Toast.makeText(getApplicationContext(), "未满足红包使用条件", 0)
								.show();
						return;
					}
				}
				for (int i = 0; i < bonusList.getChildCount(); i++) {
					((CheckBox) bonusList.getChildAt(i).findViewById(
							R.id.checkbox)).setChecked(false);
				}
				((CheckBox) bonusList.getChildAt(arg2).findViewById(
						R.id.checkbox)).setChecked(true);
				selectedBouns = arg2;
			}
		});
		Bundle bundle = getIntent().getExtras();
		order_id = getIntent().getStringExtra("order_id");
		rec_ids = bundle.getString("rec_ids");
		names = bundle.getStringArrayList("goods_name");
		price = bundle.getStringArrayList("goods_price");
		num = bundle.getStringArrayList("goods_num");
		if ((rec_ids == null || rec_ids.equals("")) && order_id == null) {
			Toast.makeText(getApplicationContext(), "生成订单出错", 0).show();
		} else {
		}
		if (LoginActivity.isNetworkAvailable(getApplicationContext())) {
			dialog = LoginActivity.createLoadingDialog(this, R.string.loading);
			dialog.show();
			if (order_id == null) {
				checkOrder();
			} else {
				payAgainInfo(order_id);
			}
		} else {
			Toast.makeText(getApplicationContext(), "无网络链接", 0).show();
		}
		OnClickListener onClickListener = new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				switch (v.getId()) {
				case R.id.address:
					Intent intent = new Intent(getApplicationContext(),
							AddressManageActivity.class);
					startActivity(intent);
					break;
				case R.id.back_button:
					finish();
					break;

				default:
					break;
				}
			}
		};
		addressLayout.setOnClickListener(onClickListener);
		findViewById(R.id.back_button).setOnClickListener(onClickListener);
	}

	/**
	 * call alipay sdk pay. 调用SDK支付
	 * 
	 */
	public void pay() {
		/**
		 * 完整的符合支付宝参数规范的订单信�?
		 */
		if (payInfo == null || payInfo.equals("")) {
			return;
		}
		payInfo = new String(Base64.decode(payInfo, Base64.DEFAULT));
		Log.i("info", payInfo);
		Runnable payRunnable = new Runnable() {

			@Override
			public void run() {
				// 构�?�PayTask 对象
				PayTask alipay = new PayTask(PayActivity.this);
				// 调用支付接口，获取支付结�?
				String result = alipay.pay(payInfo, true);
				Message msg = new Message();
				msg.what = SDK_PAY_FLAG;
				msg.obj = result;
				mHandler.sendMessage(msg);
			}
		};

		// 必须异步调用
		Thread payThread = new Thread(payRunnable);
		payThread.start();
	}

	/**
	 * get the sdk version. 获取SDK版本�?
	 * 
	 */
	public void getSDKVersion() {
		PayTask payTask = new PayTask(this);
		String version = payTask.getVersion();
		Toast.makeText(this, version, Toast.LENGTH_SHORT).show();
	}

	/**
	 * 原生的H5（手机网页版支付切natvie支付�? 【对应页面网页支付按钮�??
	 * 
	 * @param v
	 */
	public void h5Pay(View v) {
		Intent intent = new Intent(this, H5PayDemoActivity.class);
		Bundle extras = new Bundle();
		/**
		 * url是测试的网站，在app内部打开页面是基于webview打开的，demo中的webview是H5PayDemoActivity�?
		 * demo中拦截url进行支付的�?�辑是在H5PayDemoActivity中shouldOverrideUrlLoading方法实现�?
		 * 商户可以根据自己的需求来实现
		 */
		String url = "http://youyouyiku.com";
		// url可以是一号店或�?�美团等第三方的购物wap站点，在该网站的支付过程中，支付宝sdk完成拦截支付
		extras.putString("url", url);
		intent.putExtras(extras);
		startActivity(intent);

	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		if (!(dialog != null && dialog.isShowing())) {
			if ((rec_ids == null || rec_ids.equals("")) && order_id == null) {
				Toast.makeText(getApplicationContext(), "生成订单出错", 0).show();
			}
			if (LoginActivity.isNetworkAvailable(getApplicationContext())) {
				dialog = LoginActivity.createLoadingDialog(this,
						R.string.loading);
				dialog.show();
				if (order_id == null) {
					checkOrder();
				} else {
					payAgainInfo(order_id);
				}
			} else {
				Toast.makeText(getApplicationContext(), "无网络链接", 0).show();
			}
		}
		super.onResume();
	}

	public void checkOrder() {
		final List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
		nameValuePairs.add(new BasicNameValuePair("act", "check_order"));
		nameValuePairs.add(new BasicNameValuePair("rec_ids", rec_ids));
		new Thread(new Runnable() {

			@Override
			public void run() {
				// TODO Auto-generated method stub
				try {
					PostData postData = new PostData();
					JSONObject jsonObject = postData.getJsonObject(
							CartActivity.CART_PATH, new UrlEncodedFormEntity(
									nameValuePairs, HTTP.UTF_8));
					if (jsonObject.getString("error").equals(
							MainActivity.NO_ERROR)) {
						jsonObject = jsonObject.getJSONObject("content");
						totalFee = jsonObject.getString("shipping_total");
						address = jsonObject.getString("shipping_address");
						tel = jsonObject.getString("tel");
						name = jsonObject.getString("consignee");
						mHandler.sendEmptyMessage(CHECK_ORDER);
					} else if (jsonObject.getString("message").contains("地址")) {
						handler.sendEmptyMessage(NO_ADDRES);
					}
				} catch (UnsupportedEncodingException e) {
					// TODO Auto-generated catch block
					mHandler.sendEmptyMessage(-1);
					e.printStackTrace();
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					mHandler.sendEmptyMessage(-1);
					e.printStackTrace();
				}
			}
		}).start();
	}

	protected void getHongBao() {
		// TODO Auto-generated method stub
		dialog = LoginActivity.createLoadingDialog(this, R.string.loading);
		dialog.show();
		final List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
		nameValuePairs.add(new BasicNameValuePair("act", "bonus_list"));
		new Thread(new Runnable() {

			@Override
			public void run() {
				// TODO Auto-generated method stub
				try {
					PostData postData = new PostData();
					JSONObject jsonObject = postData
							.getJsonObject(HongBaoActivity.BONUS_PATH,
									new UrlEncodedFormEntity(nameValuePairs,
											HTTP.UTF_8));
					try {
						if (jsonObject == null
								|| !jsonObject.getString("error").equals("0")) {
							handler.sendEmptyMessage(FAIL);
							return;
						} else {
							JSONArray array = jsonObject
									.getJSONArray("content");
							bonusMaps.clear();
							for (int i = 0; i < array.length(); i++) {
								if (Long.parseLong(array.getJSONObject(i)
										.getString("used_time")) > 0) {
									continue;
								}
								Map<String, String> map = new HashMap<String, String>();
								map.put("use_end_date", OrderAdapter
										.timestampToDate(array.getJSONObject(i)
												.getString("use_end_date")));
								map.put("bonus_sn", array.getJSONObject(i)
										.getString("bonus_sn"));
								map.put("type_name", array.getJSONObject(i)
										.getString("type_name"));
								map.put("type_money", array.getJSONObject(i)
										.getString("type_money"));
								map.put("min_goods_amount",
										"满"
												+ array.getJSONObject(i)
														.getString(
																"min_goods_amount")
												+ "可以使用");
								map.put("min_amount", array.getJSONObject(i)
										.getString("min_goods_amount"));
								map.put("use_start_date", OrderAdapter
										.timestampToDate(array.getJSONObject(i)
												.getString("use_start_date")));
								map.put("bonus_id", array.getJSONObject(i)
										.getString("bonus_id"));
								map.put("used_time", array.getJSONObject(i)
										.getString("used_time"));

								bonusMaps.add(map);
							}
							handler.sendEmptyMessage(SUCCEED);
						}
					} catch (JSONException e) {
						// TODO Auto-generated catch block
						handler.sendEmptyMessage(FAIL);
						e.printStackTrace();
					}
				} catch (UnsupportedEncodingException e) {
					// TODO Auto-generated catch block
					handler.sendEmptyMessage(FAIL);
					e.printStackTrace();
				}
			}
		}).start();
	}

	public void getOrder(View v) {
		// TODO Auto-generated method stub
		dialog = LoginActivity.createLoadingDialog(this, R.string.loading);
		dialog.show();
		if (order_id != null) {
			handler.sendEmptyMessage(PAY_AGAIN);
			return;
		}
		final List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
		nameValuePairs.add(new BasicNameValuePair("act", "buy"));
		nameValuePairs.add(new BasicNameValuePair("rec_ids", rec_ids));
		if (selectedBouns >= 0 && selectedBouns < bonusMaps.size()) {
			nameValuePairs.add(new BasicNameValuePair("bonus_id", bonusMaps
					.get(selectedBouns).get("bonus_id")));
			Log.i("id", bonusMaps.get(selectedBouns).get("bonus_id"));
		}
		Log.i("rec_ids", rec_ids);
		new Thread(new Runnable() {

			@Override
			public void run() {
				// TODO Auto-generated method stub
				try {
					PostData postData = new PostData();
					JSONObject jsonObject = postData.getJsonObject(
							CartActivity.CART_PATH, new UrlEncodedFormEntity(
									nameValuePairs, HTTP.UTF_8));
					Log.i("json", jsonObject.toString());
					if (jsonObject.getString("error").equals(
							MainActivity.NO_ERROR)) {
						payInfo = jsonObject.getJSONObject("content")
								.getString("data");
						handler.sendEmptyMessage(GET_ORDER_CMP);
						return;
					} else {
						handler.sendEmptyMessage(GET_ORDER_FAIL);
					}
				} catch (UnsupportedEncodingException e) {
					// TODO Auto-generated catch block
					handler.sendEmptyMessage(NET_ERR);
					e.printStackTrace();
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					handler.sendEmptyMessage(NET_ERR);
					e.printStackTrace();
				}
			}
		}).start();

	}

	public void payAgain(String order_id) {
		final List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
		nameValuePairs.add(new BasicNameValuePair("act", "pay_again"));
		nameValuePairs.add(new BasicNameValuePair("order_id", order_id));
		new Thread(new Runnable() {

			@Override
			public void run() {
				// TODO Auto-generated method stub
				try {
					PostData postData = new PostData();
					JSONObject jsonObject = postData.getJsonObject(
							CartActivity.CART_PATH, new UrlEncodedFormEntity(
									nameValuePairs, HTTP.UTF_8));
					Log.i("json", jsonObject.toString());
					if (jsonObject.getString("error").equals(
							MainActivity.NO_ERROR)) {
						payInfo = jsonObject.getJSONObject("content")
								.getString("data");
						handler.sendEmptyMessage(GET_ORDER_CMP);
						return;
					} else {
						handler.sendEmptyMessage(GET_ORDER_FAIL);
					}
				} catch (UnsupportedEncodingException e) {
					// TODO Auto-generated catch block
					handler.sendEmptyMessage(NET_ERR);
					e.printStackTrace();
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					handler.sendEmptyMessage(NET_ERR);
					e.printStackTrace();
				}
			}
		}).start();
	}

	public void payAgainInfo(String order_id) {
		final List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
		nameValuePairs.add(new BasicNameValuePair("act", "detail"));
		nameValuePairs.add(new BasicNameValuePair("order_id", order_id));
		new Thread(new Runnable() {

			@Override
			public void run() {
				// TODO Auto-generated method stub
				try {
					PostData postData = new PostData();
					JSONObject jsonObject = postData.getJsonObject(
							OrderActivity.ORDER_PATH, new UrlEncodedFormEntity(
									nameValuePairs, HTTP.UTF_8));
					Log.i("json", jsonObject.toString());
					if (jsonObject.getString("error").equals(
							MainActivity.NO_ERROR)) {
						jsonObject = jsonObject.getJSONObject("content");
						totalFee = jsonObject.getString("order_amount");
						address = jsonObject.getString("address");
						tel = jsonObject.getString("tel");
						name = jsonObject.getString("consignee");
						JSONArray jsonArray = jsonObject
								.getJSONArray("goods_list");
						names = new ArrayList<String>();
						num = new ArrayList<String>();
						price = new ArrayList<String>();
						for (int i = 0; i < jsonArray.length(); i++) {
							names.add(jsonArray.getJSONObject(i).getString(
									"goods_name"));
							num.add(jsonArray.getJSONObject(i).getString(
									"goods_number"));
							price.add(jsonArray.getJSONObject(i).getString(
									"goods_price"));

						}
						mHandler.sendEmptyMessage(CHECK_ORDER);
						return;
					} else {
						mHandler.sendEmptyMessage(-1);
					}
				} catch (UnsupportedEncodingException e) {
					// TODO Auto-generated catch block
					mHandler.sendEmptyMessage(NET_ERR);
					e.printStackTrace();
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					mHandler.sendEmptyMessage(NET_ERR);
					e.printStackTrace();
				}
			}
		}).start();
	}

	@TargetApi(Build.VERSION_CODES.KITKAT)
	private void setTranslucentStatus(boolean on) {
		Window win = getWindow();
		WindowManager.LayoutParams winParams = win.getAttributes();
		final int bits = WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS;
		if (on) {
			winParams.flags |= bits;
		} else {
			winParams.flags &= ~bits;
		}
		win.setAttributes(winParams);
	}@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		MainActivity.sendNotification(this);
		super.onPause();
	}
}
